<template>
    <LayoutWrap class="permission">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="90px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="关键词" prop="keyName">
                        <el-select
                            class="custom-the-select_key"
                            popper-class="custom-the-select-popper_key"
                            v-model="formSearch.keyName"
                            placeholder="请选择"
                            style="width: 105px;margin-right: 10px;"
                        >
                            <el-option
                                v-for="item in keyOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.keyValue"
                            placeholder="请输入关键字检索"
                            @keyup.enter.native="getList"
                            style="width: 206px"
                        ></el-input>
                    </el-form-item>
                </div>
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="驾驶员" prop="driver">
                        <el-select
                            v-model="formSearch.driver"
                            filterable
                            clearable
                            placeholder="请选择"
                            style="width: 322px"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in optionsPersons"
                                :key="item._id"
                                :label="item.name"
                                :value="item._id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间区间" prop="startDate">
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.startDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'startDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="起始时间"
                            v-model="formSearch.startTime"
                            class="custom-the-datepicker"
                            style="width: 60px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'startTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                        <span style="display: inline-block; padding: 0 5px;">-</span>
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.endDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'endDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="结束时间"
                            v-model="formSearch.endTime"
                            class="custom-the-datepicker"
                            style="width: 60px; margin-right: 5px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'endTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                    </el-form-item>
                </div>
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间快捷项" prop="selectMenu">
                        <el-select
                            style="width: 322px"
                            v-model="formSearch.selectMenu"
                            placeholder="请选择"
                            :popper-append-to-body="false"
                            clearable
                            @change="onChangeTimeRange"
                            @clear="onChangeTimeRange('All')"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in menuOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间类型" prop="dateType">
                        <el-select
                            v-model="formSearch.dateType"
                            filterable
                            placeholder="请选择"
                            style="width: 322px"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in optionsDateTypes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>

                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="排序方式" prop="sortType">
                        <el-select
                            @change="setOrderSortType"
                            v-model="formSearch.sortType"
                            filterable
                            placeholder="请选择"
                            style="width: 322px"
                        >
                            <el-option
                                v-for="item in optionsSortTypes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="数量范围" prop="keyName">
                        <el-input
                            v-model="formSearch.numberStart"
                            @keyup.enter.native="getList"
                            style="width: 105px;"
                        ></el-input>
                        <span style="display: inline-block; margin: 0 15px">-</span>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.numberEnd"
                            @keyup.enter.native="getList"
                            style="width: 105px;"
                        ></el-input>
                    </el-form-item>
                </div>

                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="数量类型" prop="numberType">
                        <el-select v-model="formSearch.numberType" filterable placeholder="请选择" style="width: 322px">
                            <el-option
                                v-for="item in optionsNumberTypes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="getList">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <ul class="list-head">
            <li class="list-head-item">
                <el-button style="min-width:80px;" @click="onClickDetail(dataSourceDefault, '添加')" type="primary"
                    >添加</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    @click="
                        multipleAddVisible = true;
                        multipleCreateSelection = [
                            {...dataSourceDefault, uuid: uuidv4()},
                            {...dataSourceDefault, uuid: uuidv4()}
                        ];
                    "
                    type="primary"
                    >批量添加</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleUpdateVisible = true"
                    type="primary"
                    >批量修改</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleDeleteVisible = true"
                    type="danger"
                    >批量删除</el-button
                >
            </li>
        </ul>

        <el-table
            v-loading="isLoading"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            ref="multipleUpdateTable"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" :index="indexMethod"></el-table-column>
            <el-table-column prop="licensePlate" label="车牌号" sortable></el-table-column>
            <el-table-column prop="brandType" label="品牌型号" sortable></el-table-column>
            <el-table-column prop="driver" label="驾驶员" sortable>
                <template v-slot="{row}">
                    {{ row.driverInfo && row.driverInfo.name }}
                </template>
            </el-table-column>
            <el-table-column prop="price" label="车辆价格" sortable></el-table-column>
            <el-table-column prop="bodyColor" label="车身颜色" sortable></el-table-column>
            <el-table-column prop="mileage" label="行驶里程" sortable></el-table-column>
            <el-table-column prop="engineNumber" label="发动机号" sortable></el-table-column>
            <el-table-column prop="frameNumber" label="车架号" sortable></el-table-column>
            <el-table-column prop="manufacturer" label="生产厂家" sortable></el-table-column>
            <el-table-column prop="dateOfProduction" label="出厂日期" sortable>
                <template v-slot="{row}">
                    {{ row.dateOfProduction | formatShortDate }}
                </template>
            </el-table-column>
            <el-table-column prop="dateAnnualInspectionExpiration" label="年检到期" sortable>
                <template v-slot="{row}">
                    {{ row.dateAnnualInspectionExpiration | formatShortDate }}
                </template>
            </el-table-column>
            <el-table-column prop="dateExpirationOfInsurance" label="保险到期" sortable>
                <template v-slot="{row}">
                    {{ row.dateExpirationOfInsurance | formatShortDate }}
                </template>
            </el-table-column>
            <el-table-column prop="emissionLevel" label="排放等级" sortable></el-table-column>
            <el-table-column prop="status" label="车辆状态" sortable>
                <template v-slot="{row}">{{ row.status | showCarStatus }}</template>
            </el-table-column>
            <el-table-column prop="ownership" label="车辆归属" sortable>
                <template v-slot="{row}">{{ row.ownership | showCarOwnership }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column prop="operatorDate" label="操作时间" sortable>
                <template v-slot="{row}">
                    {{ row.operatorDate | formatDateFillStr }}
                </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" sortable>
                <template v-slot="{row}">{{ row.operator && row.operator.name }}</template>
            </el-table-column>
            <el-table-column prop="date" label="创建时间" sortable>
                <template v-slot="{row}">
                    {{ row.date | formatDateFillStr }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template v-slot="{row}">
                    <el-button :disabled="isMultSelect" @click="onClickDetail(row, '编辑车辆')" type="text">
                        编辑
                    </el-button>
                    <el-button :disabled="isMultSelect" @click="onClickDelete(row)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <FunctionDialog
            :title="title"
            @on-ok="getList"
            :visible.sync="visibleDetail"
            :data-source="dataSourceDetail"
            :optionsPersons="optionsPersons"
        ></FunctionDialog>
        <TheElDialog title="删除车辆" :visible.sync="dialogVisible">
            <span>你确定删除 {{ dataSourceDetail.name }} 吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="dialogLoading" @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="onClickOkDelete(dataSourceDetail)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
        <TheElDialog title="批量添加" :visible.sync="multipleAddVisible" minWidth @closed="isMultipleLoading = false">
            <div v-loading="isMultipleLoading">
                <el-button style="width: 100%;margin-bottom: 10px;" type="primary" @click="onPushSelection">
                    +1 行数据
                </el-button>
            </div>
            <el-table :data="multipleCreateSelection" :border="false" style="width: 100%">
                <el-table-column prop="licensePlate" label="车牌号">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车牌号</template>
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_licensePlate_${row.uuid}`"
                            :ref="`form_licensePlate_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="licensePlate" label="">
                                <el-input v-model="row.licensePlate" placeholder=""></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="brandType" label="品牌型号">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>品牌型号</template>
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_brandType_${row.uuid}`"
                            :ref="`form_brandType_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="brandType" label="">
                                <el-input v-model="row.brandType" placeholder=""></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="driver" label="驾驶员">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>驾驶员</template>
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_driver_${row.uuid}`"
                            :ref="`form_driver_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="driver" label="">
                                <el-select
                                    v-model="row.driver"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in optionsPersons"
                                        :key="item._id"
                                        :label="item.name"
                                        :value="item._id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="车辆状态">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车辆状态</template>
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_status_${row.uuid}`"
                            :ref="`form_status_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="status" label="">
                                <el-select
                                    v-model="row.status"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in CAR_STATUS"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="ownership" label="车辆归属">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车辆归属</template>
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_ownership_${row.uuid}`"
                            :ref="`form_ownership_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="ownership" label="">
                                <el-select
                                    v-model="row.ownership"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in CAR_OWNERSHIPS"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_remark_${row.uuid}`"
                            :ref="`form_remark_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="remark" label="">
                                <el-input
                                    type="textarea"
                                    rows="1"
                                    :show-word-limit="row.remark ? row.remark && row.remark.length > 150 : false"
                                    :maxlength="200"
                                    v-model="row.remark"
                                    placeholder=""
                                ></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveAddSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleAddVisible = false">取 消</el-button>
                <el-button
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkCreate(multipleCreateSelection)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
        <TheElDialog
            title="批量修改"
            :visible.sync="multipleUpdateVisible"
            minWidth
            @closed="handleSelectionChange(multipleValueSelection)"
        >
            <el-table :data="multipleSelection" :border="false" style="width: 100%">
                <el-table-column prop="licensePlate" label="车牌号">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车牌号</template>

                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_licensePlate_${row.uuid}`"
                            :ref="`form_licensePlate_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="licensePlate" label="">
                                <el-input v-model="row.licensePlate" placeholder=""></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="brandType" label="品牌型号">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>品牌型号</template>

                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_brandType_${row.uuid}`"
                            :ref="`form_brandType_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="brandType" label="">
                                <el-input v-model="row.brandType" placeholder=""></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="driver" label="驾驶员">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>驾驶员</template>

                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_driver_${row.uuid}`"
                            :ref="`form_driver_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="driver" label="">
                                <el-select
                                    v-model="row.driver"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in optionsPersons"
                                        :key="item._id"
                                        :label="item.name"
                                        :value="item._id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="车辆状态">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车辆状态</template>

                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_status_${row.uuid}`"
                            :ref="`form_status_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="status" label="">
                                <el-select
                                    v-model="row.status"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in CAR_STATUS"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="ownership" label="车辆归属">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>车辆归属</template>

                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_ownership_${row.uuid}`"
                            :ref="`form_ownership_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="ownership" label="">
                                <el-select
                                    v-model="row.ownership"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in CAR_OWNERSHIPS"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_remark_${row.uuid}`"
                            :ref="`form_remark_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="remark" label="">
                                <el-input
                                    type="textarea"
                                    rows="1"
                                    :show-word-limit="row.remark ? row.remark && row.remark.length > 150 : false"
                                    :maxlength="200"
                                    v-model="row.remark"
                                    placeholder=""
                                ></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveUpdateSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleUpdateVisible = false">取 消</el-button>
                <el-button
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkUpdate(multipleSelection)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
        <TheElDialog
            title="批量删除"
            :visible.sync="multipleDeleteVisible"
            minWidth
            @closed="handleSelectionChange(multipleValueSelection)"
        >
            <span>你确定删除下面车辆吗？</span>
            <el-table v-loading="isMultipleLoading" :data="multipleSelection" :border="false" style="width: 100%">
                <el-table-column prop="licensePlate" label="车牌号" sortable></el-table-column>
                <el-table-column prop="brandType" label="品牌型号" sortable></el-table-column>
                <el-table-column prop="driver" label="驾驶员" sortable>
                    <template v-slot="{row}">
                        {{ row.driverInfo && row.driverInfo.name }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="车辆状态" sortable>
                    <template v-slot="{row}">{{ row.status | showCarStatus }}</template>
                </el-table-column>
                <el-table-column prop="ownership" label="车辆归属" sortable>
                    <template v-slot="{row}">{{ row.ownership | showCarOwnership }}</template>
                </el-table-column>
                <el-table-column prop="remark" label="备注"> </el-table-column>
                <el-table-column align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveUpdateSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleDeleteVisible = false">取 消</el-button>
                <el-button
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkDelete(multipleSelection)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {mapGetters} from 'vuex';
import {getApiList, postApisList, putApisList, deleteApiById, deleteApiByIds} from '@/api/car';
import {getApiList as getPersons} from '@/api/person';
import FunctionDialog from '@/views/system/car/FunctionDialog';
import {THE_MOMENT_YYYYMMDD_HHMMSS} from '@/utils/constant';
import {deepCopy} from '@/utils/utils';
import {v4 as uuidv4} from 'uuid';
import moment from 'moment';
import getRules from '@/views/system/car/getRules';
import {CAR_OWNERSHIPS, CAR_STATUS} from '@/views/system/car/constant';

const dataSourceDefault = {
    id: undefined,
    licensePlate: undefined,
    brandType: undefined,
    driver: undefined,
    price: undefined,
    bodyColor: undefined,
    mileage: undefined,
    engineNumber: undefined,
    frameNumber: undefined,
    manufacturer: undefined,
    dateOfProduction: undefined,
    dateAnnualInspectionExpiration: undefined,
    dateExpirationOfInsurance: undefined,
    emissionLevel: undefined,
    status: undefined,
    ownership: undefined,
    remark: undefined
};

function getOrderSortType() {
    return localStorage.getItem('OrderSortType');
}
function setOrderSortType(value) {
    localStorage.setItem('OrderSortType', value);
}

export default {
    name: 'order',
    components: {
        FunctionDialog
    },
    filters: {
        showCarStatus(value) {
            const target = CAR_STATUS.filter(i => i.value === value)[0];
            return target ? target.label : '';
        },
        showCarOwnership(value) {
            const target = CAR_OWNERSHIPS.filter(i => i.value === value)[0];
            return target ? target.label : '';
        }
    },
    data() {
        return {
            CAR_OWNERSHIPS,
            CAR_STATUS,
            uuidv4,
            THE_MOMENT_YYYYMMDD_HHMMSS,
            formSearch: {
                startDate: '',
                startTime: '',
                endDate: '',
                endTime: '',

                selectMenu: 'All', // 'CustomTime' 'LastWeek',
                driver: '',

                numberType: 'price',
                numberStart: '',
                numberEnd: '',

                sortType: getOrderSortType() || 'PositiveOrder',

                dateType: 'operatorDate',
                keyName: 'licensePlate',
                keyValue: '',
                pageSize: 10,
                page: 1,
                count: 0
            },
            keyOptions: [
                {label: '车牌号', value: 'licensePlate', disabled: false},
                {label: '品牌型号', value: 'brandType', disabled: false},
                {label: '车身颜色', value: 'bodyColor', disabled: false},
                {label: '发动机号', value: 'engineNumber', disabled: false},
                {label: '车架号', value: 'frameNumber', disabled: false},
                {label: '生产厂家', value: 'manufacturer', disabled: false},
                {label: '排放等级', value: 'emissionLevel', disabled: false},
                {label: '备注', value: 'remark', disabled: false}
            ],
            tableData: [],
            isLoading: false,
            dataSourceDefault,
            dataSourceDetail: {...dataSourceDefault},
            visibleDetail: false,
            title: '添加',
            dialogVisible: false,
            dialogLoading: false,
            multipleSelection: [],
            multipleValueSelection: [],
            multipleDeleteVisible: false, // 批量删除打开、关闭
            isMultipleLoading: false,
            multipleUpdateVisible: false,
            multipleAddVisible: false,
            multipleCreateSelection: [
                {...dataSourceDefault, uuid: uuidv4()},
                {...dataSourceDefault, uuid: uuidv4()}
            ],
            RULES: getRules(),
            optionsPersons: [],
            optionsDateTypes: [
                {label: '操作时间', value: 'operatorDate'},
                {label: '创建时间', value: 'date'},
                {label: '出厂日期', value: 'dateOfProduction'},
                {label: '年检到期', value: 'dateAnnualInspectionExpiration'},
                {label: '保险到期', value: 'dateExpirationOfInsurance'}
            ],
            optionsNumberTypes: [
                {label: '车辆价格', value: 'price'},
                {label: '行驶里程', value: 'mileage'}
            ],
            optionsSortTypes: [
                {label: '时间顺序', value: 'PositiveOrder'},
                {label: '时间倒序', value: 'ReverseOrder'}
            ]
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        }),
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    created() {
        const result = new Array(12).fill('').map((item, index) => {
            const month = (index + 1).toString();
            return {
                label: `${month}月份`,
                value: `${month}`,
                method: (month => () => {
                    month = month.padStart(2, '0');
                    const startDate = moment().format(`YYYY-${month}-01`);
                    const endDate = moment(startDate)
                        .endOf('month')
                        .format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                })(month)
            };
        });

        this.menuOptions = [
            {
                label: '所有时间',
                value: 'All',
                method: () => {
                    this.formSearch = {
                        ...this.formSearch,
                        startDate: '',
                        startTime: '',
                        endDate: '',
                        endTime: ''
                    };
                }
            },
            {label: '自定义时间', value: 'CustomTime', method: () => {}},
            {
                label: '今天',
                value: 'Today',
                method: () => {
                    const startDate = moment().format('YYYY-MM-DD');
                    const endDate = startDate;

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '昨天',
                value: 'Yesterday',
                method: () => {
                    const startDate = moment()
                        .add(-1, 'days')
                        .format('YYYY-MM-DD');
                    const endDate = startDate;

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '最近一月',
                value: 'LastMonth',
                method: () => {
                    const startDate = moment()
                        .add(-30, 'days')
                        .format('YYYY-MM-DD');
                    const endDate = moment().format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            }
        ];
        this.menuOptions.push(...result);

        // const selectMenu = `${moment().format('MM') - 0}`;
        // this.formSearch.selectMenu = selectMenu;

        // const target = this.menuOptions.find(item => item.value === selectMenu);
        // target && target.method();

        this.getPersons().then(res => {
            // const data = res.find(item => item.name === '诗洞配送服务站');
            // if (data) {
            //     this.formSearch.driver = data._id;
            // }
        });
        this.getList();
    },
    methods: {
        setOrderSortType,
        onChangeTimeRange(value) {
            const target = this.menuOptions.find(item => item.value === value);
            if (target && target.method) {
                target.method();
            }
        },
        onChangeDate(value, type) {
            this.formSearch.selectMenu = 'CustomTime';

            if (type === 'startDate' && !value) {
                this.formSearch = {...this.formSearch, startTime: ''};
            }
            if (type === 'startDate' && value && !this.formSearch.startTime) {
                this.formSearch = {...this.formSearch, startTime: '00:00'};
            }
            if (type === 'endDate' && !value) {
                this.formSearch = {...this.formSearch, endTime: ''};
            }
            if (type === 'endDate' && value && !this.formSearch.endTime) {
                this.formSearch = {...this.formSearch, endTime: '24:00'};
            }
        },
        getPersons() {
            const newItem = {page: 1, pageSize: 1000, isDeleted: false, sort: '-date', select: '_id name -operator'};
            return getPersons(newItem)
                .then(({data: res}) => {
                    this.optionsPersons = res.data;
                    return res.data;
                })
                .catch(error => {
                    console.log('error', error);
                });
        },
        indexMethod(index) {
            return index + 1 + (this.formSearch.page - 1) * this.formSearch.pageSize;
        },
        onRemoveAddSelection(row) {
            this.multipleCreateSelection = this.multipleCreateSelection.filter(({uuid}) => uuid !== row.uuid);
        },
        onRemoveUpdateSelection(row) {
            this.multipleSelection = this.multipleSelection.filter(({uuid}) => uuid !== row.uuid);
            this.multipleValueSelection = this.multipleValueSelection.filter(({uuid}) => uuid !== row.uuid);
            const tRow = this.tableData.find(item => row._id && item._id === row._id);
            tRow && this.$refs.multipleUpdateTable.toggleRowSelection(tRow, false);
        },
        onPushSelection() {
            this.multipleCreateSelection.push({...dataSourceDefault, uuid: uuidv4()});
        },
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        resetForm() {
            const formSearch = this.$options.data().formSearch;

            this.formSearch = {
                ...this.formSearch,
                ...formSearch
            };
        },
        handleSelectionChange(value) {
            this.multipleValueSelection = value;
            this.multipleSelection = deepCopy(value).map(item => {
                item.uuid = uuidv4();
                return item;
            });
        },
        // 批量删除
        onClickMultipleOkDelete(multipleSelection) {
            this.isMultipleLoading = true;
            deleteApiByIds(multipleSelection.map(item => item._id))
                .then(res => {
                    this.getList();
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: '批量删除失败'});
                    console.error(error);
                })
                .finally(() => {
                    this.isMultipleLoading = false;
                    this.multipleDeleteVisible = false;
                });
        },
        async formValidates(values) {
            const handers = [];
            values.forEach(item => {
                const uuid = item.uuid;
                const formNames = [
                    `form_licensePlate_${uuid}`,
                    `form_brandType_${uuid}`,
                    `form_driver_${uuid}`,
                    `form_status_${uuid}`,
                    `form_ownership_${uuid}`,
                    `form_remark_${uuid}`
                ];
                formNames.forEach(formName => {
                    if (!this.$refs[formName]) {
                        console.warn('formName', formName);
                        return;
                    }
                    const hander = new Promise((resolve, reject) => {
                        this.$refs[formName].validate((valid, fields) => {
                            if (valid) {
                                resolve(valid);
                                return;
                            }
                            reject(valid);
                        });
                    });
                    handers.push(hander);
                });
            });
            await Promise.all(handers);
        },
        // 批量添加
        async onClickMultipleOkCreate(multipleCreateSelection) {
            if (multipleCreateSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量添加失败'});
                return;
            }
            try {
                await this.formValidates(multipleCreateSelection);
                this.isMultipleLoading = true;

                postApisList(
                    multipleCreateSelection.map(item => {
                        item.datetime = new Date(moment(item.datetime).format('YYYY-MM-DD'));
                        return item;
                    })
                )
                    .then(res => {
                        this.getList();
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量添加成功'});
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;

                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量添加失败'});
                        }
                        console.log(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 批量修改
        async onClickMultipleOkUpdate(multipleSelection) {
            if (multipleSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量修改失败'});
                return;
            }
            try {
                await this.formValidates(multipleSelection);
                this.isMultipleLoading = true;
                putApisList(
                    multipleSelection.map(item => {
                        item.datetime = new Date(moment(item.datetime).format('YYYY-MM-DD'));
                        return item;
                    })
                )
                    .then(res => {
                        this.getList();
                        this.multipleUpdateVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量修改成功'});
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量修改失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 获取列表数据
        getList() {
            this.isLoading = true;
            const formSearch = this.formSearch;
            const newItem = {
                driver: formSearch.driver || undefined,
                remark: formSearch.remark || undefined,
                pageSize: formSearch.pageSize,
                page: formSearch.page,
                isDeleted: false,
                sort: formSearch.sortType === 'ReverseOrder' ? `-${formSearch.dateType}` : formSearch.dateType
            };

            const dateType = formSearch.dateType;
            if (dateType && (formSearch.startDate || formSearch.endDate)) {
                newItem[dateType] = {};

                if (formSearch.startDate) {
                    newItem[dateType].gte = new Date(
                        `${moment(formSearch.startDate).format('YYYY-MM-DD')} ${formSearch.startTime}`
                    ).getTime();
                }
                if (formSearch.endDate) {
                    newItem[dateType].lt = new Date(
                        `${moment(formSearch.endDate).format('YYYY-MM-DD')} ${formSearch.endTime}`
                    ).getTime();
                }
            }
            const numberType = formSearch.numberType;

            if (numberType && (formSearch.numberStart || formSearch.numberEnd)) {
                newItem[numberType] = {};

                if (formSearch.numberStart) {
                    newItem[numberType].gte = formSearch.numberStart - 0;
                }
                if (formSearch.numberEnd) {
                    newItem[numberType].lte = formSearch.numberEnd - 0;
                }
            }

            if (formSearch.keyValue) {
                newItem[formSearch.keyName] = formSearch.keyValue;
            }
            getApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, count, page, pageSize} = res;
                        this.tableData = data;

                        this.formSearch = {...this.formSearch, page, pageSize, count};
                    }
                })
                .catch(error => {
                    console.log(error);
                    this.tableData = [];
                    this.$message({showClose: true, type: 'error', message: `${error.name}: ${error.message}`});
                })
                .finally(() => (this.isLoading = false));
        },

        onClickDetail(row, title) {
            this.title = title;
            this.visibleDetail = true;
            this.dataSourceDetail = {...row};
        },
        onClickDelete(row) {
            this.dialogVisible = true;
            this.dataSourceDetail = {...row};
        },
        onClickOkDelete(row) {
            this.dialogLoading = true;
            deleteApiById(row._id)
                .then(res => {
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                    this.dialogLoading = false;
                })
                .catch(err => {
                    this.$message({showClose: true, type: 'error', message: '删除失败'});
                    console.log('err :', err);
                    this.dialogVisible = false;
                    this.dialogLoading = false;
                });
        }
    }
};
</script>

<style lang="scss" scoped>
.custom-the-datepicker,
.custom-the-select_time,
.custom-the-select_key {
    ::v-deep {
        .el-input__inner {
            padding-left: 10px;
            padding-right: 10px;
        }
    }
}
</style>
